import React, { useState } from 'react';
import { Row, Col, Tabs, Table, Badge } from 'antd';
import LineStackChart from 'src/components/Chart/LineStackChart';
import PieDoughnutChart from 'src/components/Chart/PieDoughnut';
import FilterTool from 'src/components/FilterTool';
import '../../../StrategyLabs/Detail/index.less';
import services from 'src/services/api';
import { round, bitTrans } from 'src/utils/utils';

import { tooltipFormatter } from '../utils';

import moment from 'moment';
const { TabPane } = Tabs;
export default function MiddlewareMonitor() {
  const [type, setType] = useState('elasticsearch'); // 类型，redis，mongodb，elasticsearch, mysql等

  // const [redisSlow, setRedisSlow] = useState([]); //redis.slow
  // const [redisConnection, setRedisConnection] = useState([]); //redis.connection

  const [esSharding, setEsSharding] = useState([]); //elasticsearch.sharding
  const [esIndex, setEsIndex] = useState([]); //elasticsearch.index
  const [esStorage, setEsStorage] = useState([]); //elasticsearch.storage

  // const [mysqlSlow, setMysqlSlow] = useState([]); //mysql.slow
  // const [mysqlConnection, setMysqlConnection] = useState([]); //mysql.connection
  // const [mysqlIo, setMysqlIo] = useState([]); //mysql.io

  const [kafkaProduce, setKafkaProduce] = useState([]);
  const [kafkaConsume, setKafkaConsume] = useState([]);
  const [kafkaDelay, setKakaDelay] = useState([]);

  // const [redisNodes, setRedisNodes] = useState([]);
  const [esNodes, setEsNodes] = useState([]);

  const filterItems = [
    {
      type: 'rangepicker',
      key: 'start',
      name: ['start', 'end'],
      label: '时间',
      defaultValue: [
        moment()
          .subtract(6, 'day')
          .startOf('day')
          .format('YYYY-MM-DD HH:mm'),
        moment().format('YYYY-MM-DD HH:mm'),
      ],
      disabledDate: (current) => {
        return (
          current &&
          (current > moment().endOf('day') ||
            current <
              moment()
                .subtract(30, 'day')
                .endOf('day'))
        );
        // return current && current > moment().endOf('day');
      },
      ranges: {
        本周: [moment().startOf('week'), moment()],
        近7天: [moment().subtract('days', 6), moment()],
        本月: [moment().startOf('month'), moment()],
        近30天: [moment().subtract('days', 29), moment()],
      },
      format: 'YYYY-MM-DD HH:mm',
      placeholder: ['起始时间', '结束时间'],
      allowClear: false,
    },
  ];

  // 获取redis的数据
  // function getRedis(params, type = true) {
  //   if (!type) return;
  //   getStatistics({ sub_type: 'slow', ...params });
  //   getStatistics({ sub_type: 'connection', ...params });
  //   services.devOpt
  //     .nodeList({
  //       type: 'redis',
  //     })
  //     .then((data) => {
  //       setRedisNodes(data.data);
  //     });
  // }

  // 获取es的数据
  function getElasticsearch(params, type = true) {
    if (!type) return;
    getStatistics({ sub_type: 'sharding', ...params });
    getStatistics({ sub_type: 'index', ...params });
    getStatistics({ sub_type: 'storage', ...params });
    services.devOpt
      .nodeList({
        type: 'elasticsearch',
      })
      .then((data) => {
        setEsNodes(data.data || []);
      });
  }

  // 获取mysql的数据
  // function getMysql(params, type = true) {
  //   if (!type) return;
  //   getStatistics({ sub_type: 'slow', ...params });
  //   getStatistics({ sub_type: 'connection', ...params });
  //   getStatistics({ sub_type: 'io', ...params });
  // }

  function getKafka(params, type = true) {
    if (!type) return;
    getStatistics({ sub_type: 'produce', ...params });
    getStatistics({ sub_type: 'consume', ...params });
    getStatistics({ sub_type: 'delay', ...params });
  }

  function getStatistics(params) {
    services.devOpt.middlewareMonitor({ type: type, ...params }).then((res) => {
      if (res.code === 0) {
        switch (type) {
          // case 'redis':
          //   switch (params.sub_type) {
          //     case 'slow':
          //       setRedisSlow(res.data);
          //       break;
          //     case 'connection':
          //       setRedisConnection(res.data);
          //       break;
          //     default:
          //       break;
          //   }
          //   break;
          case 'elasticsearch':
            switch (params.sub_type) {
              case 'sharding':
                setEsSharding(res.data);
                break;
              case 'index':
                setEsIndex(res.data);
                break;
              case 'storage':
                setEsStorage(res.data);
                break;
              default:
                break;
            }
            break;
          // case 'mysql':
          //   switch (params.sub_type) {
          //     case 'slow':
          //       setMysqlSlow(res.data);
          //       break;
          //     case 'connection':
          //       setMysqlConnection(res.data);
          //       break;
          //     case 'io':
          //       setMysqlIo(res.data);
          //       break;
          //     default:
          //       break;
          //   }
          //   break;

          case 'kafka':
            switch (params.sub_type) {
              case 'produce':
                setKafkaProduce(res.data);
                break;
              case 'consume':
                setKafkaConsume(res.data);
                break;
              case 'delay':
                setKakaDelay(res.data);
                break;
              default:
                break;
            }
            break;
          default:
            break;
        }
      }
    });
  }

  const esStorageTotal = esStorage.reduce((total, it) => {
    total += Number(it.value);
    return total;
  }, 0);
  const [unit, bitNum] = bitTrans(esStorageTotal, 'B');

  const esStorageTotalX = esStorage.reduce((total, it) => {
    total += round(Number(it.value) / bitNum, 2) * 100;
    return total;
  }, 0);

  return (
    <Tabs activeKey={type} onChange={(key) => setType(key)} destroyInactiveTabPane>
      {/* <TabPane tab='Redis监控' key='redis'>
        <div className='detail-page'>
          <FilterTool
            data={filterItems}
            colNum={4}
            query={getRedis}
            refreshFilter={getRedis}
            isOnChange={true}
            justify='start'
          />
          <Row gutter={20} style={{ marginTop: '20px' }}>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>慢查询</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='redisSlow'
                    width='100%'
                    height='300px'
                    dataSource={Object.keys(redisSlow).length > 0 ? redisSlow : []}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>连接数</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='redisConnection'
                    width='100%'
                    height='300px'
                    dataSource={redisConnection}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>节点状态</h4>
                </div>
                <div className='chart-box'>
                  <Table
                    dataSource={redisNodes}
                    pagination={{ pageSize: 4 }}
                    columns={[
                      { dataIndex: 'instance', title: '节点IP', key: 'instance' },
                      {
                        dataIndex: 'status',
                        title: '状态',
                        key: 'status',
                        render(val) {
                          return <Badge status={val ? 'success' : 'error'} text={val ? '正常' : '异常'} />;
                        },
                      },
                      // 隐藏[操作]列
                      // {
                      //   dataIndex: 'x',
                      //   title: '操作',
                      //   key: 'x',
                      //   render: (record, text) => {
                      //     return (
                      //       <>
                      //         <Button type='link'>停止</Button>
                      //         <Button type='link'>删除</Button>
                      //       </>
                      //     );
                      //   },
                      // },
                    ]}
                  />
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </TabPane> */}
      <TabPane tab='ES监控' key='elasticsearch'>
        <div className='detail-page'>
          <FilterTool
            data={filterItems}
            colNum={4}
            query={getElasticsearch}
            refreshFilter={getElasticsearch}
            isOnChange={true}
            justify='start'
          />
          <Row gutter={20} style={{ marginTop: '20px' }}>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>分片状态</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='esSharding'
                    width='100%'
                    height='300px'
                    dataSource={esSharding}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>索引状态</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='esIndex'
                    width='100%'
                    height='300px'
                    dataSource={esIndex}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>储存状态</h4>
                </div>
                <div className='chart-box'>
                  <PieDoughnutChart
                    id='esStorage'
                    width='100%'
                    height='300px'
                    dataSource={esStorage}
                    legend={esStorage.length > 0 ? esStorage.map((it) => it.name) : []}
                    total={{
                      title: '储存空间',
                      value: round(esStorageTotalX / 100) + unit,
                    }}
                    dataFormatter={(params) => {
                      return params.name + ':\n' + params.percent + '%(' + round(params.value / bitNum, 2) + unit + ')';
                    }}
                    tooltipFormatter={(params) => {
                      return (
                        params.marker +
                        params.name +
                        ':' +
                        params.percent +
                        '%<br/>' +
                        round(params.value / bitNum, 2) +
                        unit
                      );
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>节点状态</h4>
                </div>
                <div className='chart-box'>
                  <Table
                    dataSource={esNodes}
                    pagination={{ pageSize: 4 }}
                    columns={[
                      { dataIndex: 'instance', title: '节点IP', key: 'instance' },

                      {
                        dataIndex: 'status',
                        title: '状态',
                        key: 'status',
                        render(val) {
                          return <Badge status={val ? 'success' : 'error'} text={val ? '正常' : '异常'} />;
                        },
                      },
                      // 隐藏[操作]列
                      // {
                      //   dataIndex: 'x',
                      //   title: '操作',
                      //   key: 'x',
                      //   render: (record, text) => {
                      //     return (
                      //       <>
                      //         <Button type='link'>停止</Button>
                      //         <Button type='link'>删除</Button>
                      //       </>
                      //     );
                      //   },
                      // },
                    ]}
                  />
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </TabPane>
      {/* <TabPane tab='Mysql监控' key='mysql'>
        <div className='detail-page'>
          <FilterTool
            data={filterItems}
            colNum={4}
            query={getMysql}
            refreshFilter={getMysql}
            isOnChange={true}
            justify='start'
          />
          <Row gutter={20} style={{ marginTop: '20px' }}>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>慢查询</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='mysqlSlow'
                    width='100%'
                    height='300px'
                    dataSource={mysqlSlow}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>读写量</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='mysqlIo'
                    width='100%'
                    height='300px'
                    dataSource={mysqlIo}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey='1'
                    dataRender={(it) => {
                      const n = parseFloat(Number(it[1]).toFixed(1));
                      return Number.isNaN(n) ? 0 : n;
                    }}
                    // dataFormatter={(params) => params / 1000 + 'k'}
                    // tooltipFormatter={(params) => {
                    //   return tooltipFormatter(params, 2, [1000, 'k']);
                    // }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>连接数</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='mysqlConnection'
                    width='100%'
                    height='300px'
                    dataSource={mysqlConnection}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey='1'
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </TabPane> */}
      <TabPane tab='Kafka监控' key='kafka'>
        <div className='detail-page'>
          <FilterTool
            data={filterItems}
            colNum={4}
            query={getKafka}
            refreshFilter={getKafka}
            isOnChange={true}
            justify='start'
          />
          <Row gutter={20} style={{ marginTop: '20px' }}>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>生产流量数量</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='kafkaProduce'
                    width='100%'
                    height='300px'
                    dataSource={kafkaProduce}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey={1}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    dataFormatter={`{value}条`}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 0, [1, '条']);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>消费流量数量</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='kafakaConsume'
                    width='100%'
                    height='300px'
                    dataSource={kafkaConsume}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey='1'
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    dataFormatter={`{value}条`}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 0, [1, '条']);
                    }}
                  />
                </div>
              </div>
            </Col>
            <Col span={12} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>消费积压情况</h4>
                </div>
                <div className='chart-box'>
                  <LineStackChart
                    id='kafkaDelay'
                    width='100%'
                    height='300px'
                    dataSource={kafkaDelay}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataKey='1'
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    dataFormatter={`{value}条`}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2, [1, '条']);
                    }}
                  />
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </TabPane>
    </Tabs>
  );
}
